# -*- coding: UTF-8 -*-
# @Project ：VehicleDimensionMeasurementSystem 
# @File    ：app_thread.py
# @IDE     ：PyCharm 
# @Date    ：2024/6/12 下午10:18

from PySide6.QtCore import Qt, QTimer, QThread, Signal
from source.utils.process_file import ProcessConfigParser
from source.utils.weigh_module import WeighingModule
from source.modules import app_settings


class WaitResponseResultQThread(QThread):
    signal = Signal(dict)

    def __init__(self):
        super().__init__()

    def run(self):
        config = ProcessConfigParser()
        measurement_result = config.wait_measure_result(app_settings.RESULT_FILE_NAME)
        self.signal.emit(measurement_result)


class WeighQThread(QThread):
    """称重线程"""
    weigh_signal = Signal(dict)

    def __init__(self, serial_port, baud_rate, direction, stable_count, car_guide_weight):
        super().__init__()
        self.serial_port = serial_port
        self.baud_rate = baud_rate
        self.direction = direction
        self.stable_count = stable_count
        self.car_guide_weight = car_guide_weight

    def run(self):
        # print('执行线程！')
        weight_module = WeighingModule(self.serial_port, self.baud_rate, self.direction, self.stable_count)
        # print(weight_module)
        # weight_value = weight_module.txt_read_data(self.stable_count, self.car_guide_weight)
        # print('获取到的重量',weight_value)
        # self.weigh_signal.emit(weight_value)
        count = 0
        prev_data = None
        with open('../resources/data/Documents.txt', 'r') as read_file:
            for line in read_file.readlines():
                if count == int(self.stable_count):
                    self.weigh_signal.emit(
                        {'weight': prev_data, 'count': count, 'stable_count': self.stable_count, 'state': True,
                         'car_guide_weight': self.car_guide_weight})
                    break
                result = weight_module.process_data(line.strip(), '=', 'reverse')
                if result == prev_data:
                    count += 1
                else:
                    count = 1
                    prev_data = result
                self.weigh_signal.emit({'weight': prev_data, 'count': count, 'stable_count': self.stable_count, })